Page({
  data: {
    dialogVisible: false,
    houseList: [],
    isEmpty: false,
  },
  onShow() {
    this.getHoustList()
  },
  async getHoustList() {
    const { code, data } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      houseList: data,
      isEmpty: data.length === 0,
    })
  },
  swipeClose(ev) {
    console.log(ev)
    const { position, instance } = ev.detail
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })
      // 把当前点击的数据id和index进行记录
      this.id = ev.mark.id
      this.index = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  goDetail(e) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + e.mark.id,
    })
  },
  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
  /**
   * 弹层关闭事件
   */
  dialogClose(e) {
    if (e.detail === 'confirm') {
      // 删除
      this.deleteHouse()
    }
  },
  observers: {
    houseList(newValue) {
      console.log(newValue)
    },
  },
  /**
   * 删除房屋接口调用
   */
  async deleteHouse() {
    console.log(this.id)
    console.log(this.index)
    if (!this.id) return wx.utils.toast('参数不正确')
    const { code } = await wx.http.delete('/room/' + this.id)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    this.data.houseList.splice(this.index, 1)
    this.setData({
      houseList: this.data.houseList,
      isEmpty: this.data.houseList.length === 0,
    })
    wx.utils.toast('删除成功')
  },
})
